//
//  YBWithdrawTransferEarnViewController.m
//  Nectar
//
//  Created by famer on 2023/11/11.
//  Copyright © 2023 asance. All rights reserved.
//

#import "YBWithdrawTransferEarnViewController+LayoutConstraints.h"
#import "YBWithdrawResultViewController.h"
#import "HomeCoinManager.h"
#import "RevDataGetRechargeIncomeData.h"
#import "YBTostView.h"

@interface YBWithdrawTransferEarnViewController ()
@property (copy, nonatomic) NSString *canWithdrawAmount;
@end

@implementation YBWithdrawTransferEarnViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kWhiteColor;
    
    [self.view addSubview:self.navigationBar];
    [self.view addSubview:self.contentView];

    [self.contentView addSubview:self.topContentView];
    [self.topContentView addSubview:self.amountCanBeWithdrawnRow];
    [self.topContentView addSubview:self.amountCanBeWithdrawnTomorrowRow];
    [self.topContentView addSubview:self.avaiableWithdrawalTimesRow];

    [self.contentView addSubview:self.bottomContentView];
    [self.bottomContentView addSubview:self.enterWithdrawalAmoutLabel];
    [self.bottomContentView addSubview:self.withdrawalAmoutTextField];
    [self.bottomContentView addSubview:self.withdrawalButton];
    [self.bottomContentView addSubview:self.withdrawalTipsLabel];

    [self setLayoutConstraints];
    
    [self updateUI];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self.navigationBar resetBarItemState];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self getRechargeIncomeData];
}

#pragma mark - Private Method
- (void)updateUI{
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [self.view addGestureRecognizer:tapGestureRecognizer];
}

- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer {
    // 关闭 UIAlertController
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)getRechargeIncomeData{
    [SVProgressHUD show];
    self.view.userInteractionEnabled = NO;
    NSMutableDictionary *params = [NSDictionary baseReqParams];
    [params setObject:[HomeCoinManager shareInstance].globalCoinType forKey:@"coinType"];
    NSString *urlString = [NSString stringWithFormat:@"%@",PathGetRechargeIncomeData];
    
    [[YBHttpRequestManager shareInstance] Post:urlString params:params success:^(NSObject *resultObject) {
        NSLog(@"getRechargeIncomeData: %@",resultObject);
        
        self.view.userInteractionEnabled = YES;
        [SVProgressHUD dismiss];
        
        //判断网络是否返回错误信息
        YBResponseModel *obj = [YBResponseModel initWithResponseObject:(NSDictionary *)resultObject];
        if([obj success]){
            RevDataGetRechargeIncomeData *result = [RevDataGetRechargeIncomeData mj_objectWithKeyValues:obj.data];
            
            self.canWithdrawAmount = result.canWithdrawAmount;
            
            NSDecimalNumber *canWithdrawAmountBig = [NSDecimalNumber decimalNumberWithString:result.canWithdrawAmount];

            NSDecimalNumber *tomorrowCanWithdrawAmountBig = [NSDecimalNumber decimalNumberWithString:result.tomorrowCanWithdrawAmount];

            self.amountCanBeWithdrawnRow.valueLabel.text = [NSString stringWithFormat:@"%@ USDT", [canWithdrawAmountBig stringValue]];
            
            self.amountCanBeWithdrawnTomorrowRow.valueLabel.text = [NSString stringWithFormat:@"%@ USDT", [tomorrowCanWithdrawAmountBig stringValue]];
            
            self.avaiableWithdrawalTimesRow.valueLabel.text = [NSString stringWithFormat:@"%@", result.remindTimes];
            
        }
        
    } failure:^(NSError *error) {
        self.view.userInteractionEnabled = YES;
        YBErrorModel *yerror = [YBErrorModel ErrorObjForNSError:error];
    }];
}

- (void)extractRechargeIncomeWithPassword:(NSString *)password amount:(NSString *)amount{
    if(password==nil || password.length==0) return;
    if(amount==nil || amount.length==0) return;
    
    [SVProgressHUD show];
    self.view.userInteractionEnabled = NO;
    NSMutableDictionary *params = [NSDictionary baseReqParams];
    [params setObject:password forKey:@"password"];
    [params setObject:amount forKey:@"amount"];
    [params setObject:[HomeCoinManager shareInstance].globalCoinType forKey:@"coinType"];
    NSString *urlString = [NSString stringWithFormat:@"%@",PathExtractRechargeIncome];
    
    [[YBHttpRequestManager shareInstance] Post:urlString params:params success:^(NSObject *resultObject) {
        NSLog(@"extractRechargeIncomeWithPassword: %@",resultObject);
        
        self.view.userInteractionEnabled = YES;
        [SVProgressHUD dismiss];
        
        //判断网络是否返回错误信息
        YBResponseModel *obj = [YBResponseModel initWithResponseObject:(NSDictionary *)resultObject];
        if([obj success]){
            [self toWithdrawalResultViewController];
        }
        
    } failure:^(NSError *error) {
        self.view.userInteractionEnabled = YES;
        YBErrorModel *yerror = [YBErrorModel ErrorObjForNSError:error];
    }];
}


- (void)toTotalEarnDetailViewController{
//    YBEarnDetailTotalEarnViewController *viewcontroller = [[YBEarnDetailTotalEarnViewController alloc] init];
//    viewcontroller.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:viewcontroller animated:YES];
}

- (void)toWithdrawalResultViewController{

    // 获取当前日期并进行格式化
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd/MM/yyyy"];
    NSString *formattedDate = [dateFormatter stringFromDate:[NSDate date]];

    NSLog(@"Formatted Date: %@", formattedDate);

    YBWithdrawResultViewController *viewcontroller = [[YBWithdrawResultViewController alloc] init];
    viewcontroller.date = formattedDate;
    viewcontroller.amount = self.withdrawalAmoutTextField.text;
    viewcontroller.unit = @"USDT";
    viewcontroller.address = [HomeCoinManager shareInstance].globalAddress;
    viewcontroller.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:viewcontroller animated:YES];
}

- (void)toWithdrawalAction{
    NSDecimalNumber *amountBig = [NSDecimalNumber decimalNumberWithString:self.withdrawalAmoutTextField.text];
    NSDecimalNumber *canWithdrawAmountBig = [NSDecimalNumber decimalNumberWithString:self.canWithdrawAmount];
    if ([canWithdrawAmountBig isEqualToNumber:NSDecimalNumber.notANumber]){
        [YBTostView showWithTitle:@"The withdrawable balance is 0."];
        return;
    }
    if ([amountBig isEqualToNumber:NSDecimalNumber.notANumber]){
        [YBTostView showWithTitle:@"The withdrawal amount cannot be less than 2 USDT."];
        return;
    }

    double amountDou = [amountBig doubleValue];
    if(amountDou>2){
        [self showInputPasswordAlter];
    }else{
        [YBTostView showWithTitle:@"The withdrawal amount cannot be less than 2 USDT."];
    }
}

- (void)showInputPasswordAlter{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Enter your password" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    // 添加一个输入框
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"Please enter";
        textField.secureTextEntry = YES;
    }];
    
    // 添加取消按钮
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
//    [alertController addAction:cancelAction];
    
    // 添加确认按钮
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"Transfer" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        UITextField *textField = alertController.textFields.firstObject;

        NSString *inputText = textField.text;
        // 在这里处理用户输入的数据
        NSLog(@"User input: %@", inputText);
        if([[NSObject nullSafeForObject:inputText] length]>0){
            [self extractRechargeIncomeWithPassword:inputText
                                             amount:self.withdrawalAmoutTextField.text];
        }
    }];
    [alertController addAction:confirmAction];
    
    // 显示警告框
    [self presentViewController:alertController animated:YES completion:nil];
    
}


#pragma mark Getter Setter
YBViewGetter(contentView, _contentView, kThemeBackground);
YBViewGetter(topContentView, _topContentView, kWhiteColor);
YBViewGetter(bottomContentView, _bottomContentView, kWhiteColor);

YBLabelGetter(enterWithdrawalAmoutLabel, _enterWithdrawalAmoutLabel, [UIFont systemFontOfSize:12], @"Enter the withdrawal amount", [UIColor hexColor:@"84828C"], NSTextAlignmentLeft);

YBLabelGetter(withdrawalTipsLabel, _withdrawalTipsLabel, [UIFont systemFontOfSize:10], @"The withdrawal amount will be entered into your raw wallet, please check it in your USDT assets.", [UIColor hexColor:@"84828C"], NSTextAlignmentLeft);

- (UITextField *)withdrawalAmoutTextField{
    if(!_withdrawalAmoutTextField){
        _withdrawalAmoutTextField = [[UITextField alloc] initWithFrame:CGRectZero];
        _withdrawalAmoutTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _withdrawalAmoutTextField.borderStyle = UITextBorderStyleRoundedRect;
        _withdrawalAmoutTextField.backgroundColor = kWhiteColor;
        _withdrawalAmoutTextField.keyboardType = UIKeyboardTypeDecimalPad;
        _withdrawalAmoutTextField.layer.borderWidth = 1;
        _withdrawalAmoutTextField.layer.borderColor = [UIColor hexColor:@"F6F5F6"].CGColor;
        _withdrawalAmoutTextField.returnKeyType = UIReturnKeyDone;
        _withdrawalAmoutTextField.font = [UIFont systemFontOfSize:14];
        _withdrawalAmoutTextField.placeholder = @"Not less than 2 USDT";
        _withdrawalAmoutTextField.textColor = kThemeBlackColor;
    }
    return _withdrawalAmoutTextField;
}

- (UIButton *)withdrawalButton{
    if(!_withdrawalButton){
        _withdrawalButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _withdrawalButton.backgroundColor = kThemeColor;
        _withdrawalButton.clipsToBounds = YES;
        _withdrawalButton.layer.cornerRadius = 6;
        [_withdrawalButton setTitleColor:kWhiteColor forState:UIControlStateNormal];
        [_withdrawalButton setTitleColor:kWhiteColor forState:UIControlStateSelected];
        [_withdrawalButton setTitle:@"Withdrawal" forState:UIControlStateNormal];
        [_withdrawalButton setTitle:@"Withdrawal" forState:UIControlStateSelected];
        [_withdrawalButton addTarget:self action:@selector(toWithdrawalAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _withdrawalButton;
}

- (YBWithdrawRow *)amountCanBeWithdrawnRow{
    if(!_amountCanBeWithdrawnRow){
        _amountCanBeWithdrawnRow = [[YBWithdrawRow alloc] initWithFrame:CGRectZero];
        _amountCanBeWithdrawnRow.titleLabel.text = @"Amount that can be withdrawn";
    }
    return  _amountCanBeWithdrawnRow;
}

- (YBWithdrawRow *)amountCanBeWithdrawnTomorrowRow{
    if(!_amountCanBeWithdrawnTomorrowRow){
        _amountCanBeWithdrawnTomorrowRow = [[YBWithdrawRow alloc] initWithFrame:CGRectZero];
        _amountCanBeWithdrawnTomorrowRow.titleLabel.text = @"Amount can be withdrawn tomorrow";
    }
    return  _amountCanBeWithdrawnTomorrowRow;
}

- (YBWithdrawRow *)avaiableWithdrawalTimesRow{
    if(!_avaiableWithdrawalTimesRow){
        _avaiableWithdrawalTimesRow = [[YBWithdrawRow alloc] initWithFrame:CGRectZero];
        _avaiableWithdrawalTimesRow.titleLabel.text = @"Available withdrawal times";
    }
    return  _avaiableWithdrawalTimesRow;
}

- (YBNavigationBar *)navigationBar{
    if(!_navigationBar){
        _navigationBar = [[YBNavigationBar alloc] initWithFrame:CGRectZero];
        _navigationBar.backgroundColor = kWhiteColor;
        [_navigationBar setTitle:@"Withdraw" titleColor:kThemeBlackColor];
        [_navigationBar setLeftBarImage:@"icon_nav_back" forState:UIControlStateNormal];
        __weak __typeof(&*self)weakSelf = self;
        _navigationBar.onLeftBarButtonBlock = ^(){
            __strong __typeof(&*weakSelf)strongSelf = weakSelf;
            if(!strongSelf) return;
            
            [strongSelf.navigationController popViewControllerAnimated:YES];
        };
    }
    return _navigationBar;
}

@end
